package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;

import java.util.HashMap;

/**
 * @author GY
 * @version V1.0
 * @date 2025-03-04 16:18
 */
public class WechatServiceImpl implements WechatService {

    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.appsecret}")
    private String secret;

    @Override
    public String getOpenid(String code) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("appid",appid);
        params.put("secret",secret);
        params.put("js_code",code);
        String json = HttpUtil.get(REQUEST_URL, params);//get , 写错成post了
        if (StrUtil.isNotEmpty(json)){
            JSONObject jsonObject = JSONUtil.parseObj(json);
            if (ObjectUtil.isNotEmpty(jsonObject)&& ObjectUtil.isEmpty(jsonObject.get("errcode"))){
                return jsonObject.getStr("openid");
            }
        }
        throw new BaseException("get openid Error");
    }

    @Override
    public String getPhoneNum(String detailCode) {
        String token = getToken();
        HashMap<String, Object> params = new HashMap<>();
        params.put("code",detailCode);
        String post = HttpUtil.post(PHONE_REQUEST_URL+token, JSONUtil.toJsonStr(params));//toJsonStr写成parseObj
        if (StrUtil.isNotEmpty(post)){
            JSONObject jsonObject = JSONUtil.parseObj(post);
            if (ObjectUtil.isNotEmpty(jsonObject) && ObjectUtil.equal(jsonObject.get("errcode"),0)){//ObjectUtil.equal(jsonObject.get("errcode"),0)
                return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");//jsonObject.getJSONObject()
            }
        }
        throw new BaseException("get phoneNumber Error");
    }

    private String getToken() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("appid",appid);
        params.put("secret",secret);
        String post = HttpUtil.get(TOKEN_URL, params);
        if (StrUtil.isNotEmpty(post)){
            JSONObject jsonObject = JSONUtil.parseObj(post);
            if (ObjectUtil.isNotEmpty(jsonObject)){
                return jsonObject.getStr("access_token");
            }
        }
        throw new BaseException("get access_token Error");
    }
}
